import React, { useState,useEffect } from 'react';
import Pagecomponent from './pageComponent/Pagecomponent';
import './Users.css'


var pageNum;
var io = 1;
const Users = () => {
  //分页
  const [dataList, setDataList] = useState([]);
  const [totalPage, setTotalPage] = useState(15);

  const [users,setUsers] = useState([]);


  useEffect(()=>{
    fetch(`https://api.124ss.xyz:2355/endusers?rand=$1`,{
      method: "GET",
      mode: "cors",
      headers: {
        "Content-Type": "text/plain"
      }

    }).then(res => {
      return res.json();
    })
    .then(res =>{
      var arr = [];
      var userObj = [];
      res.forEach((item,index) => {
        userObj = [
          item['open_id'],
          item['user_name'],
          item['user_image']
        ]
        arr.push(userObj)
      });
      setUsers(arr)
      console.log(res)
    } )
    .catch((err)=>{
      console.log("err:",err);
    })
  },[]
)

  const getCurrentPage = (currentPage) => {
    setDataList(users[currentPage-1])
    pageNum = currentPage;
  }
  

  const DelItem = (idx,item) => {
  
    fetch(`https://api.124ss.xyz:2355/enddelUsers/${item[0]}`,{
      method: "delete",
      mode: "cors",
      headers: {
        "Content-Type": "text/plain"
      },
      body: JSON.stringify({
        open_id: item[0]
      })

    }).then(res => {
      return res.text();
    })
    .then(res =>{
      console.log(res);
    } )
    .catch((err)=>{
      console.log("err:",err);
    })

    let newUsers = users.filter((_,index)=>idx!=index);
    setUsers(newUsers);

  }

  return (
    <div id='users-container'>
      <div id='users-table'>
        <table id='users-tab'>
          <thead>
            <tr>
              <th>序号</th>
              <th>用户头像</th>
              <th>OPENID</th>
              <th>用户名</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
          {
            users.slice(7*(pageNum-1),7*pageNum).map((item, index) =>
              <tr key={index}>
                <td>
                  {(pageNum-1)*7+index+1}
                </td>
                <td>
                  <img style={{width: 50, height: 50}} src={item[2]} />
                </td>
                <td>{item[0]}</td>
                <td>{item[1]}</td>
                <td>
                  <button id='users-btn' onClick={() => DelItem(index,item)}>
                    移除
                  </button>
                </td>
              </tr>)
              
          }
          </tbody>
        </table>
      </div>
    
      <div id='users-page'>
        <Pagecomponent totalPage={totalPage} pageCallbackFn={getCurrentPage}/>
      </div>
    </div>
  )

}

export default Users

